#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include "../Sock/Socket.hpp"
#include "../Sock/errno.hpp"
#include "../Sock/Logmessage.hpp"
#include <fstream>
namespace ftpClient
{
    class Client
    {
        std::string ip_;
        uint16_t  port_;
        int sockfd_;
    public:
        Client(const std::string& ip,const uint16_t port)
            :ip_(ip),port_(port),sockfd_(-1)
        {}

        void init()
        {
            sockfd_=Socket::CreateSock();
        }

        void run()
        {
            if(Socket::Connect(sockfd_,ip_,port_)!=0)
            {
                logMessage(WARNING,"connect err...");
            }

            serverIO();
        }
        ~Client()
        {
            if(sockfd_>=0)
                close(sockfd_);
        }
    private:
        void serverIO()
        {
            std::string filename;
            while (true)
            {
                //输入要下载的文件名
                std::cout << "Enter-ServerRoot/*# ";
                getline(std::cin, filename);
                send(sockfd_, filename.c_str(), filename.size(),0);
                //构建保存文件路径
                std::string saveFile="ClientRoot/"+filename;
                std::ofstream out(saveFile,std::ios_base::binary);
                if(!out)
                {
                    logMessage(ERROR,"create saveFile err");
                    exit(CREATE_FILE_ERR);
                }

                char buffer[1024];
                ssize_t n=recv(sockfd_,buffer,sizeof(buffer),0);
                if(n>0)
                {   
                    out.write(buffer,n);
                }
                out.close();
            }      
        }
    };
}